package com.studio49.exmple.controller.web.sys;

import com.github.pagehelper.PageHelper;
import com.studio49.exmple.common.constant.ForwardConstant;
import com.studio49.exmple.common.constant.SysConstant;
import com.studio49.exmple.common.util.MD5Utils;
import com.studio49.exmple.common.util.PubDateUtils;
import com.studio49.exmple.core.controller.BaseController;
import com.studio49.exmple.core.entity.pub.PageView;
import com.studio49.exmple.entity.web.sys.User;
import com.studio49.exmple.entity.web.sys.UserRoleRel;
import com.studio49.exmple.mapper.web.sys.RoleMapper;
import com.studio49.exmple.mapper.web.sys.UserMapper;
import com.studio49.exmple.mapper.web.sys.UserRoleRelMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/sysUser")
public class SysUserManagerController extends BaseController {

	private static final Logger LOG = LogManager.getLogger(SysUserManagerController.class.getName());

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private UserRoleRelMapper userRoleRelMapper;

	/**
	 * 列表页
	 * @return
	 */
	@RequestMapping("/list")
	public String list(){
		return ForwardConstant.SYSTEM_H + ForwardConstant.SYS_USER + ForwardConstant.LIST;
	}
	
	/**
	 * 分页查询
	 * @param keyWords
	 * @param pageNow
	 * @param pageSize
	 * @return
	 */
	@RequestMapping({"/findByPage"})
	@ResponseBody
	public PageView findByPage(String keyWords, Integer pageNow, Integer pageSize) {
		if (pageNow == null) {
			pageNow = Integer.valueOf(1);
		}
		PageHelper.startPage(pageNow.intValue(), pageSize.intValue());
		Map params = new HashMap();
		params.put("keyWords", keyWords);

		List list = this.userMapper.findSysUser(params);

		return new PageView(list);
	}

	@RequestMapping({"addUI"})
	public String addUI(Model model) throws Exception {
		List roles = this.roleMapper.selectAll();
		model.addAttribute("roles", roles);
		return ForwardConstant.SYSTEM_H + ForwardConstant.SYS_USER + ForwardConstant.ADD;
//		return "sys/sysUser/add";
	}

	@ResponseBody
	@RequestMapping({"addEntity"})
	public String addEntity(User user) throws Exception
	{
		try {
			user.setUserType((short) 2);
			String password = user.getPassword();
			user.setPassword(MD5Utils.md5(password));

			Date now = PubDateUtils.getNow();
			user.setCreateTime(now);
			user.setModifyTime(now);

			this.userMapper.insertSelective(user);
			return SysConstant.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("添加系统用户时出错！", e); }
		return SysConstant.ERROR;
	}

	@ResponseBody
	@RequestMapping({"deleteEntity"})
	@Transactional
	public String deleteEntity(String ids) throws Exception
	{
		String[] ids_c = ids.split(",");

		for (String id : ids_c) {
			this.userMapper.deleteByPrimaryKey(id);
		}
		return SysConstant.SUCCESS;
	}

	@RequestMapping({"editUI"})
	public String editUI(Long id, Model model, HttpServletRequest request) throws Exception
	{
		User user = (User)this.userMapper.selectByPrimaryKey(id);
		model.addAttribute("user", user);

		List roles = this.roleMapper.selectAll();
		model.addAttribute("roles", roles);

		return ForwardConstant.SYSTEM_H + ForwardConstant.SYS_USER + ForwardConstant.EDIT;
//		return "sys/sysUser/edit";
	}

	@ResponseBody
	@RequestMapping({"editEntity"})
	public String editEntity(User user, String roleIds) throws Exception
	{
		try {
			String password = user.getPassword();
			if (StringUtils.isNotBlank(password))
				user.setPassword(MD5Utils.md5(password));
			else {
				user.setPassword(null);
			}
			Date now = PubDateUtils.getNow();
			user.setModifyTime(now);
			this.userMapper.updateByPrimaryKeySelective(user);

			Long userId = user.getId();

			UserRoleRel userRoleRel_del = new UserRoleRel();
			userRoleRel_del.setUserId(userId);
			this.userRoleRelMapper.delete(userRoleRel_del);

			if (StringUtils.isNotBlank(roleIds)) {
				String[] split = roleIds.split(",");
				for (String roleId : split) {
					UserRoleRel userRoleRel_ins = new UserRoleRel();
					userRoleRel_ins.setUserId(userId);
					userRoleRel_ins.setRoleId(Long.valueOf(roleId));
					this.userRoleRelMapper.insertSelective(userRoleRel_ins);
				}
			}
			return SysConstant.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("编辑系统用户时出错！", e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); }
		return SysConstant.ERROR;
	}

	@ResponseBody
	@RequestMapping({"findRoleOfUser"})
	public List<UserRoleRel> findRoleOfUser(Long userId)
			throws Exception
	{
		UserRoleRel userRoleRel = new UserRoleRel();
		userRoleRel.setUserId(userId);
		return this.userRoleRelMapper.select(userRoleRel);
	}


}
